# python
from flask import Blueprint, request, jsonify
from ..common.Result import response, response_failure
from ..models.user_info import UserInfo
from .. import db

user_info_bp = Blueprint('user_info_bp', __name__)

@user_info_bp.route('/user_info', methods=['POST'])
def create_user_info():
    data = request.get_json()
    user_info = UserInfo(**data)
    db.session.add(user_info)
    db.session.commit()
    return response(data=user_info.to_dict(), msg="User information created successfully!")

@user_info_bp.route('/user_info/<int:id>', methods=['GET'])
def get_user_info(id):
    user_info = UserInfo.query.get_or_404(id)
    return response(data=user_info.to_dict())

@user_info_bp.route('/user_info/<int:id>', methods=['PUT'])
def update_user_info(id):
    data = request.get_json()
    user_info = UserInfo.query.get_or_404(id)
    for key, value in data.items():
        if hasattr(user_info, key):
            setattr(user_info, key, value)
    db.session.commit()
    return response(msg='User information updated successfully!')

@user_info_bp.route('/user_info/<int:id>', methods=['DELETE'])
def delete_user_info(id):
    user_info = UserInfo.query.get_or_404(id)
    db.session.delete(user_info)
    db.session.commit()
    return response(msg='User information deleted successfully!')

@user_info_bp.route('/user_info/list', methods=['POST'])
def list_user_info():
    data = request.get_json()
    page = data.get('page', 1)
    per_page = data.get('per_page', 10)
    query = UserInfo.query

    if 'name' in data:
        query = query.filter(UserInfo.name.like(f"%{data['name']}%"))

    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    user_info_list = [user_info.to_dict() for user_info in pagination.items]

    return response(data={
        'user_info': user_info_list,
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': pagination.page
    })